package com.mobisys.live.im;

import com.alibaba.fastjson.JSON;
import com.mobisys.live.bean.im_group.ImportUserIdBean;
import com.mobisys.live.bean.im_group.JoinGroupBean;
import com.mobisys.live.bean.im_group.NewGroupBean;
import com.mobisys.live.config.Config;
import com.mobisys.live.http.RestTemplateUtil;
import com.mobisys.live.response.tim.JoinGroupResponse;
import com.mobisys.live.response.tim.TimResponse;
import com.mobisys.live.response.tim.CreateGroupResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Created by zhuo on 2018-01-24.
 * 腾讯云即时通信相关的一些方法的封装
 */
public class TimRestApi {
    private static Logger logger = LogManager.getLogger();
    //开放IM https接口参数, 一般不需要修改
    protected static String http_type = "https://";
    protected static String method = "post";
    protected static String im_yun_url = "console.tim.qq.com";
    protected static String version = "v4";
    protected static String contenttype = "json";
    protected static String apn = "0";


    //群组操作相关的url
    private static final String GROUP_URL = "https://console.tim.qq.com/v4/group_open_http_svc/";

    //帐号相关
    private static final String ACCOUNT_URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import";


    public TimResponse api(String service_name, String cmd_name, String identifier, String usersig, String req_data) {
        //$req_tmp用来做格式化输出
        //$req_tmp = json_decode($req_data, true);
        //构建HTTP请求参数，具体格式请参考 REST API接口文档 (http://avc.qcloud.com/wiki/im/)(即时通信云-数据管理REST接口)
        String parameter = "usersig=" + usersig
                + "&identifier=" + identifier
                + "&sdkappid=" + Config.IMSDK_APPID
                + "&random=99999999"
                + "&contenttype=" + contenttype;
        String url = GROUP_URL + cmd_name + "?" + parameter;
        RestTemplate restTemplate = RestTemplateUtil.restTemplate();
        TimResponse response = restTemplate.postForObject(url, req_data, TimResponse.class);

        return response;

    }

    /**
     * 将我们系统的帐号导入到腾讯云即时通信里面，一般在用户注册我们的系统后调用
     *
     *
     * @param importUserIdBean
     * @return (0表示请求成功)
     * {
     * "ActionStatus":"OK",
     * "ErrorInfo":"",
     * "ErrorCode":0
     * }
     */


    public static TimResponse importToIM( ImportUserIdBean importUserIdBean) {
        String parameter = "usersig=" + TlsSignature.genTLSSig(Config.IMSDK_ACCOUNT_ADMIN)
                + "&identifier=" + Config.IMSDK_ACCOUNT_ADMIN
                + "&sdkappid=" + Config.IMSDK_APPID
                + "&random=99999999"
                + "&contenttype=" + contenttype;
        String url = ACCOUNT_URL + "?" + parameter;

        RestTemplate restTemplate = new RestTemplate();
        //String userSig=TlsSignature.genTLSSig(Config.IMSDK_ACCOUNT_ADMIN);




        logger.debug("url:" + url);
        logger.debug("request:" + importUserIdBean);

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);

        //会将请求体里面的大写首字母自动转成小写
        HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(importUserIdBean), headers);
        logger.debug(JSON.toJSONString(importUserIdBean));
        logger.debug(entity);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        logger.debug("http code:" + responseEntity.getStatusCode());
        logger.debug("http value:" + responseEntity.getStatusCodeValue());
        String responseStr = responseEntity.getBody();
        logger.debug("response:" + responseStr);
        JSONObject jsonObject = new JSONObject(responseStr);

        TimResponse response = new CreateGroupResponse();
        response.setErrorCode(jsonObject.getInt("ErrorCode"));
        response.setActionStatus(jsonObject.getString("ActionStatus"));
        response.setErrorInfo(jsonObject.getString("ErrorInfo"));

        return response;
    }


    /**
     * 创建群组
     *
     * @param userSig      用户sig，由TlsSignature产生
     * @param identifier   管理员的用户名，Config.IMSDK_ACCOUNT_ADMIN
     * @param newGroupBean
     * @return
     */
    public static CreateGroupResponse groupCreateGroup(String userSig, String identifier, NewGroupBean newGroupBean) {
        String parameter = "usersig=" + userSig
                + "&identifier=" + identifier
                + "&sdkappid=" + Config.IMSDK_APPID
                + "&random=99999999"
                + "&contenttype=" + contenttype;
        String url = GROUP_URL + "create_group?" + parameter;


        RestTemplate restTemplate = new RestTemplate();
        /*MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
        restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);*/

        logger.debug("url:" + url);
        logger.debug("request:" + newGroupBean);
        //CreateGroupResponse response=restTemplate.postForObject(url, null, CreateGroupResponse.class);
        /*CreateGroupResponse response=restTemplate.postForObject(url, newGroupBean, CreateGroupResponse.class);
        CreateGroupResponse response=restTemplate.postForEntity(url, newGroupBean, CreateGroupResponse.class);*/

       /* ResponseEntity<TimResponse> responseEntity=restTemplate.postForEntity(url,newGroupBean,TimResponse.class);
        logger.debug("http code:"+responseEntity.getStatusCode());
        logger.debug("http value:"+responseEntity.getStatusCodeValue());
        TimResponse response=responseEntity.getBody();
        logger.debug("response:"+response);*/
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);

        //会将请求体里面的大写首字母自动转成小写
        HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(newGroupBean), headers);
        logger.debug(JSON.toJSONString(newGroupBean));
        logger.debug(entity);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        logger.debug("http code:" + responseEntity.getStatusCode());
        logger.debug("http value:" + responseEntity.getStatusCodeValue());
        String responseStr = responseEntity.getBody();
        logger.debug("response:" + responseStr);
        JSONObject jsonObject = new JSONObject(responseStr);

        CreateGroupResponse response = new CreateGroupResponse();
        response.setErrorCode(jsonObject.getInt("ErrorCode"));
        response.setActionStatus(jsonObject.getString("ActionStatus"));

        if (jsonObject.has("ErrorInfo")) {
            response.setErrorInfo(jsonObject.getString("ErrorInfo"));
        }

        if (response.getErrorCode() == 0) {
            response.setGroupId(jsonObject.getString("GroupId"));
        } else {
            response.setGroupId(null);
        }
        return response;
    }


    /**
     * @param userSig
     * @param newGroupBean
     * @return
     */
    public static CreateGroupResponse groupCreateGroup(String userSig, NewGroupBean newGroupBean) {
        return groupCreateGroup(userSig, Config.IMSDK_ACCOUNT_ADMIN, newGroupBean);
    }

    /**
     * @param newGroupBean
     * @return
     */
    public static CreateGroupResponse groupCreateGroup(NewGroupBean newGroupBean) {
        String userSig = TlsSignature.genTLSSig(Config.IMSDK_ACCOUNT_ADMIN);
        return groupCreateGroup(userSig, Config.IMSDK_ACCOUNT_ADMIN, newGroupBean);
    }


   /* */

    /**
     * 用户加入群组
     *
     * @param userSig       用户sig，由TlsSignature产生
     * @param identifier    管理员的用户名，Config.IMSDK_ACCOUNT_ADMIN
     * @param joinGroupBean
     * @return
     *//*
    public static JoinGroupResponse joinGroupResponse(String userSig, String identifier, JoinGroupBean joinGroupBean) {

        public static JoinGroupResponse joinGroup(String userSig, String identifier, JoinGroupBean joinGroupBean){
            //构建HTTP请求参数，具体格式请参考 REST API接口文档 (http://avc.qcloud.com/wiki/im/)(即时通信云-数据管理REST接口)
            String parameter = "usersig=" + userSig
                    + "&identifier=" + identifier
                    + "&sdkappid=" + Config.IMSDK_APPID
                    + "&random=99999999"
                    + "&contenttype=" + contenttype;
            String url = GROUP_URL + "create_group" + "?" + parameter;
            RestTemplate restTemplate = new RestTemplate();
            logger.debug("url:" + url);
            logger.debug("request:" + joinGroupBean);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, joinGroupBean, String.class);
            logger.debug("http code:" + responseEntity.getStatusCode());
            logger.debug("http value:" + responseEntity.getStatusCodeValue());
            String responseStr = responseEntity.getBody();
            logger.debug("response:" + responseStr);
            JSONObject jsonObject = new JSONObject(responseStr);
            JoinGroupResponse response = new JoinGroupResponse();
            response.setErrorCode(jsonObject.getInt("ErrorCode"));
            response.setActionStatus(jsonObject.getString("ActionStatus"));
            response.setErrorInfo(jsonObject.getString("ErrorInfo"));
            response.setMemberList(jsonObject.getString("Member_Account"));
            response.setResult(jsonObject.getInt("Result"));
            if (response.getErrorCode() == 0) {
                response.setGroupId(jsonObject.getString("GroupId"));
            } else {
                response.setGroupId(null);
            }
            return response;
        }
     */
    public static JoinGroupResponse joinGroup(String userSig, String identifier, JoinGroupBean joinGroupBean) {
        //构建HTTP请求参数，具体格式请参考 REST API接口文档 (http://avc.qcloud.com/wiki/im/)(即时通信云-数据管理REST接口)
        String parameter = "usersig=" + userSig
                + "&identifier=" + identifier
                + "&sdkappid=" + Config.IMSDK_APPID
                + "&random=99999999"
                + "&contenttype=" + contenttype;
        String url = GROUP_URL + "create_group" + "?" + parameter;
        RestTemplate restTemplate = new RestTemplate();
        logger.debug("url:" + url);
        logger.debug("request:" + joinGroupBean);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, joinGroupBean, String.class);
        logger.debug("http code:" + responseEntity.getStatusCode());
        logger.debug("http value:" + responseEntity.getStatusCodeValue());
        String responseStr = responseEntity.getBody();
        logger.debug("response:" + responseStr);
        JSONObject jsonObject = new JSONObject(responseStr);
        JoinGroupResponse response = new JoinGroupResponse();
        response.setErrorCode(jsonObject.getInt("ErrorCode"));
        response.setActionStatus(jsonObject.getString("ActionStatus"));
        response.setErrorInfo(jsonObject.getString("ErrorInfo"));
        response.setMemberList(jsonObject.getString("Member_Account"));
        response.setResult(jsonObject.getInt("Result"));
        if (response.getErrorCode() == 0) {
            response.setGroupId(jsonObject.getString("GroupId"));
        } else {
            response.setGroupId(null);
        }
        return response;
    }


}

